package com.chenyuxin.ilp.service.user.Impl;

import com.chenyuxin.ilp.model.constant.UserSuccessConstant;
import com.chenyuxin.ilp.model.pojo.Result;
import com.chenyuxin.ilp.model.vo.user.CaptchaVo;
import com.chenyuxin.ilp.service.user.CaptchaService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.MemoryCacheImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Iterator;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class CaptchaServiceImpl implements CaptchaService {
    @Autowired
    private DefaultKaptcha kaptcha;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    // 生成验证码
    public Result generateCaptcha() {
        // 生成验证码文本
        String text = kaptcha.createText();
        // 生成验证码图片
        BufferedImage image = kaptcha.createImage(text);
        // 转换图片为 Base64
        // 转换成 Base64（压缩为 JPEG）
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpeg");
        if (!writers.hasNext()) {
            throw new IllegalStateException("No JPEG writers available");
        }
        ImageWriter writer = writers.next();
        ImageWriteParam param = writer.getDefaultWriteParam();
        param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
        param.setCompressionQuality(0.3f); // 0.0 (最差) 到 1.0 (最好)，这里设为 50% 质量

        writer.setOutput(new MemoryCacheImageOutputStream(baos));
        try {
            writer.write(null, new javax.imageio.IIOImage(image, null, null), param);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        writer.dispose();
        String base64Image = Base64.getEncoder().encodeToString(baos.toByteArray());
        // 生成唯一 key 存储验证码
        String key = "captcha:" + UUID.randomUUID().toString().replace("-","");
        stringRedisTemplate.opsForValue().set(key,text , 5, TimeUnit.MINUTES);
        CaptchaVo captchaVo = new CaptchaVo();
        captchaVo.setKey(key);
        captchaVo.setBase64Image("data:image/jpeg;base64,"+base64Image);
        return Result.ok(UserSuccessConstant.GENERATE_CAPTCHA_REGISTER_SUCCESS,captchaVo);
    }
    // 检查验证码
    public Boolean verifyCaptcha(String key, String inputCode) {
        String code = stringRedisTemplate.opsForValue().get(key);
        if (!inputCode.equals(code)) {
            return false;
        }
        stringRedisTemplate.delete(key);
        return true;
    }
}
